package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.beans.PatientIdBean;
import com.hxkcloud.patient.popup.CalendarPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.UrlAddress;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.StringUtil;
import com.hxkcloud.patient.utils.Utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by ray_lei on 2016/8/16.
 * 问卷量表
 */
public class QuestionAssessActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_view;

    private WebView webView;
    private ProgressBar pb_web;

    private String url;
    private String title;
    private String questionId = "";
    private String questionUserId = "";
    private String userUuid = "";
    private String patientId = "";
    private String isFromRemind = "";
    private String answerType = "3";
    private boolean isFinish = false;//是否答题后关闭此页面,护士测评

    private String isFromView = "";//是否是 预览界面
    private PopupWindow viewCommentPopup;
    private Button viewBtn;
    private Button commentPBtn;
    private Button cancelBtn;
    private View view_divider;
    private Button commentNBtn;
    private View view1_divider;

    private String isFromAssistant = "";
    private boolean isSendNurse = false;//提交后是否toast已发送责任护士

    private CalendarPopWindow calendarView;
    private boolean isDoctorTest = false;//护士测评
    private boolean isUserTest = false;//用户自评

    private String createTime = "";

    private boolean isScale;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_SCALELISTUSE_SUCCESS:
                if (msg.obj != null) {
                    toastMsg(R.string.send_already);
                } else {
                    toastMsg(R.string.functionsuccess);
                }
                finish();
                break;
            case MessageCode.NETWORKCODE_SCALELISTUSE_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.functionfail);
                }
                break;
            case MessageCode.NETWORKCODE_QUESTIONLISTUSE_SUCCESS:
                if (msg.obj != null) {
                    toastMsg(R.string.send_already);
                } else {
                    toastMsg(R.string.functionsuccess);
                }
                finish();
                break;
            case MessageCode.NETWORKCODE_QUESTIONLISTUSE_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.functionfail);
                }
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_articledetail);

        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        questionId = getIntent().getStringExtra("questionId");
        if (getIntent().hasExtra("questionUserId")) {
            questionUserId = getIntent().getStringExtra("questionUserId");
        }
        patientId = getIntent().getStringExtra("patientId");
        isFromRemind = getIntent().getStringExtra("isFromRemind");
        isFromView = getIntent().getStringExtra("isFromView");

        if (getIntent().hasExtra("isFromAssistant")) {
            isFromAssistant = getIntent().getStringExtra("isFromAssistant");
        }
        isSendNurse = getIntent().getBooleanExtra("isSendNurse", false);
        if (getIntent().hasExtra("answerType")) {
            answerType = getIntent().getStringExtra("answerType");
        }

        isScale = getIntent().getBooleanExtra("isScale", false);
        isFinish = getIntent().getBooleanExtra("finishnext", false);

        initView();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_view = (TextView) findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(title);
        if ("true".equals(isFromView)) {
            tv_view.setText("下一步");
            tv_view.setVisibility(View.VISIBLE);
            tv_view.setOnClickListener(this);
        }

        webView = (WebView) findViewById(R.id.webview_article);
        pb_web = (ProgressBar) findViewById(R.id.pb_article);

        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true); //支持js
        webSettings.setUseWideViewPort(true);  //将图片调整到适合webview的大小
        webSettings.setSupportZoom(true);  //支持缩放
        webSettings.setDomStorageEnabled(true);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                pb_web.setProgress(newProgress);
                if (newProgress == 100) {
                    pb_web.setVisibility(View.INVISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                System.out.println(url);
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                System.out.println(url);
                return super.onJsConfirm(view, url, message, result);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("url======"+url);
                if (url.contains("patientInfo")) {
                    questionUserId = url.split("=")[1];
                    if ("true".equals(isFromRemind)) {
                        if (isSendNurse) {
                            toastMsg("已发送责任护士");
                        }
                        finish();
                    } else {
                        if (ScaleQuestionActivity.questionKind == 0) {//量表
                            StringUtil.zhugeTrack(mContext, "提醒-量表-护士测评-提交按钮", "护士测评提交数");
                            StringUtil.zhugeTrack(mContext, "提醒模块中类型为量表的提醒项", "统计量表按钮点击数");
                        } else if (ScaleQuestionActivity.questionKind == 1) {//调查问卷
                            StringUtil.zhugeTrack(mContext, "提醒-调查问卷-护士测评-提交按钮", "护士测评提交数");
                        }

                        Intent intent = new Intent(QuestionAssessActivity.this,
                                AssessFeedbackActivity.class);
                        intent.putExtra("assessId", questionId);
                        intent.putExtra("patientId", patientId);
                        intent.putExtra("questionUserId", questionUserId);
                        intent.putExtra("back", true);
                        intent.putExtra("come", 2);
                        startActivityForResult(intent, 100);
                        if (isFinish) {
                            finish();
                        }
                    }

                    return true;
                } else if (url.contains("backInfo")) {
                    finish();
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        url = url + "&questionId=" + questionId + "&questionUserId=" + questionUserId + "&userId=" + loginInfo.getUserId() + "&acctType=" + loginInfo.getUserStyle();
        webView.loadUrl(url);
        initPopup();

        if (calendarView == null) {
            calendarView = new CalendarPopWindow(this);
        }
        calendarView.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                createTime = Utils.date2TimeStamp(calendar, "yyyy-MM-dd");
                long createTimeL = Long.valueOf(createTime);
                Calendar calendar1 = Calendar.getInstance();
                long nowTime = calendar1.getTime().getTime();
                if (createTimeL > nowTime) {
                    toastMsg(R.string.selectdatecantlaterthannow);
                    return;
                }
                if (isDoctorTest) {
                    isDoctorTest = false;
                    Intent intent1 = new Intent(mContext, QuestionAssessActivity.class);
                    intent1.putExtra("url", UrlAddress.H5_QUESTIONASSESS_URL + "&isEdit=0" + "&patientId=" + patientId);
                    intent1.putExtra("title", mContext.getResources().getString(R.string.assessment));
                    intent1.putExtra("questionId", questionId);
                    intent1.putExtra("patientId", patientId);
                    intent1.putExtra("finishnext", true);
                    startActivity(intent1);
                    if (isFinish || "true".equals(isFromView)) {
                        Intent iBack = new Intent();
                        iBack.putExtra("back", true);
                        setResult(RESULT_OK, iBack);
                        finish();
                    }
                }
                if (isUserTest) {
                    isUserTest = false;
                    if (questionId != null) {
                        if (!TextUtils.isEmpty(patientId)) {
                            List<PatientIdBean> patients = new ArrayList<>();
                            PatientIdBean pidb = new PatientIdBean();
                            pidb.setPatientId(patientId);
                            patients.add(pidb);
                            loading();
                            if (isScale) {
                                YiJiaHuNetWorkUtils.scaleListUse(patients, questionId, createTime, handler);
                            } else {
                                YiJiaHuNetWorkUtils.questionListUse(patients, questionId, createTime, handler);
                            }

                        } else {
                            Intent iPatient = new Intent(mContext, ChooseUserActivity.class);
                            startActivityForResult(iPatient, 123);
                        }
                    }
                }

            }
        });
        calendarView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isDoctorTest = false;
                isUserTest = false;
                BrightnessUtils.lightOn(QuestionAssessActivity.this);
            }
        });
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    private void initPopup() {
        viewCommentPopup = new PopupWindow(this);
        View viewPopup = LayoutInflater.from(this).inflate(R.layout.popup_view_comment_select, null);
        viewCommentPopup.setContentView(viewPopup);

        viewCommentPopup.setWidth(screenWidth);
        viewCommentPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        viewCommentPopup.setFocusable(true);
        viewCommentPopup.setTouchable(true);
        viewCommentPopup.setOutsideTouchable(true);
        viewCommentPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));
        viewCommentPopup.setAnimationStyle(R.style.popupwindow_anim_default);

        viewBtn = (Button) viewPopup.findViewById(R.id.select_btn_view);
        commentPBtn = (Button) viewPopup.findViewById(R.id.select_btn_commentp);
        cancelBtn = (Button) viewPopup.findViewById(R.id.select_btn_cancel);
        view_divider = viewPopup.findViewById(R.id.view_select_btn_comment);
        commentNBtn = (Button) viewPopup.findViewById(R.id.select_btn_commentn);
        view1_divider = viewPopup.findViewById(R.id.view_select_btn_commentn);

        viewBtn.setVisibility(View.GONE);
        view1_divider.setVisibility(View.GONE);

        viewBtn.setOnClickListener(this);
        commentPBtn.setOnClickListener(this);
        commentNBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);

        if (TextUtils.isEmpty(patientId)) {
            view_divider.setVisibility(View.GONE);
        }
        if ("true".equals(isFromAssistant)) {
            commentNBtn.setVisibility(View.GONE);
            view_divider.setVisibility(View.GONE);
        }

        viewCommentPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(QuestionAssessActivity.this);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                if (url.contains("isEdit=1")) {
                    finish();
                } else {
                    webView.loadUrl("javascript:back()");
//                    finish();
                }
                break;
            case R.id.tv_title_func:
                viewCommentPopup.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                BrightnessUtils.lightOff(QuestionAssessActivity.this);
                break;

            case R.id.select_btn_commentp:
                if (answerType.equals("1")) {
                    toastMsg(R.string.onlynurseassess);
                    return;
                }
                viewCommentPopup.dismiss();
                isUserTest = true;
//                calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                BrightnessUtils.lightOff(this);
                calendarView.showBottom(ll_title);

                break;
            case R.id.select_btn_commentn:
                if (answerType.equals("2")) {
                    toastMsg(R.string.onlypatientassess);
                    return;
                }
                viewCommentPopup.dismiss();
                isDoctorTest = true;
//                calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                BrightnessUtils.lightOff(this);
                calendarView.showBottom(ll_title);

                break;
            case R.id.select_btn_cancel:
                viewCommentPopup.dismiss();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (url.contains("isEdit=1")) {
                finish();
            } else {
                webView.loadUrl("javascript:back()");
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (data != null) {
                List<String> ps = data.getStringArrayListExtra("patients");
                List<PatientIdBean> patients = new ArrayList<>();
                for (String p : ps) {
                    PatientIdBean pb = new PatientIdBean();
                    pb.setPatientId(p);
                    patients.add(pb);
                }
                loading();
                if (isScale) {
                    YiJiaHuNetWorkUtils.scaleListUse(patients, questionId, createTime, handler);
                } else {
                    YiJiaHuNetWorkUtils.questionListUse(patients, questionId, createTime, handler);
                }

            }
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                if (data.getBooleanExtra("back", false)) {
                    Intent iBack = new Intent();
                    iBack.putExtra("back", true);
                    setResult(RESULT_OK, iBack);
                    finish();
                }
            }
        }
    }
}
